// app.js
var mqtt = require("/utils/mqtt.js") //引入mqtt文件
function randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = $chars.length;
    var pwd = '';
    for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}
//连接配置
const options = {
    connectTimeout: 4000, //超时时间
    clientId: randomString(30), //随机生成ID
    username: '', //用户名
    password: '', //密码
}

App({
    onLaunch() {
        if (!wx.cloud) {
            console.error('请使用2.2.3')
        } else {
            wx.cloud.init({
                env: 'mybiyesheji-1g9dugc1e05b04c4',
                traceUser: true,
            })
        }


        // 展示本地存储能力
        const logs = wx.getStorageSync('logs') || []
        logs.unshift(Date.now())
        wx.setStorageSync('logs', logs)

        // 登录
        var that = this;
        var client = mqtt.connect(that.globalData.wss_url, options) //你自己的域名
        wx.cloud.callFunction({
                name: 'login',
                data: {},
                complete: function (res) {},
                success: function (res) {
                    console.log(res),
                        console.log("当前登录者openid为：" + res.result.userInfo.openId);
                    wx.setStorage({
                        key: "myOpenID",
                        data: res.result.userInfo.openId,
                    })
                },
                fail: function (err) {
                    console.error("云函数调用失败[" + err + "]");
                }
        }),
        
        /*客户端连接*/
        client.on('connect', (e) => {
            console.log('成功连接服务器!')
        })
        
        /*订阅主题*/
        client.subscribe(this.globalData.sub, {
            qos: 0
        }, function (err) {
            if (!err) {
                console.log("订阅成功:esp8266")
            }
        })
        /*客户端接收 */
        client.on('message', function (topic, message, packet) {
            that.globalData.mqttData = packet.payload.toString()
            that.globalData.mqttJSON = JSON.parse(that.globalData.mqttData)
        })

    },
    globalData: {
        userInfo: null,
        openid: null,
        mqttData: null,
        mqttJSON:[],
        FLAG_link:false,
        sub: '/mysmarthome/sub',
        wss_url: 'wxs://mqtt.kldmqttssledu.xyz:8084/mqtt/',
    }
})